# @Author: Eric Ito
# @Date: 1/30/2009
# @Name: Project Euler Problem 37


"""
The number 3797 has an interesting property. Being prime itself,
it is possible to continuously remove digits from left to right, and
remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work
from right to left: 3797, 379, 37, and 3.

Find the sum of the only eleven primes that are both truncatable from left
to right and right to left.
"""

from util import getPrimes
from util import isPrime


def truncLtoR(prime):
    while prime >= 1:
        if not isPrime(prime):
            return False
        modval = 10**(len(str(prime))-1)
        prime = prime % modval
    return True

def truncRtoL(prime):
    while prime >= 1:
        if not isPrime(prime):
            return False
        prime /= 10
    return True

def main():
    count = 0
    truncs = []
    for i in range(1000001,7,-1):
        if isPrime(i):
            if truncLtoR(i) and truncRtoL(i):
                count += 1
                truncs.append(i)
                #if count == 11:
                #    break
    print truncs
    print sum(truncs)

if __name__ == "__main__":
    main()